<?php

namespace App\Http\Controllers\Import;

use Exception;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Facades\Excel;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;


class Import implements ToCollection
{
    public $data;
    protected $delTitle;

    /**
     *
     * @param $title integer   //去掉几行标题  默认一行
     */
    public function __construct($delTitle = 1)
    {
        $this->delTitle = $delTitle;
    }

    /**
     * @param Collection $rows
     * @2020/3/23 9:53
     */
    public function collection(Collection $rows)
    {
        $this->delTitle($rows);
        //$rows 是数组格式
        $this->data = $rows; //去除多余空白行数据  需要config 文件下 的 excel.php  修改  ignore_empty 的值为null
    }

    public function delTitle (&$rows) {
        $rows = $rows->slice($this->delTitle)->values();
    }


    
    /**
     * 处理数据 (有图片的情况)
     * @param $file_name  上传文件名 
     * @param $file_dir  存放文件夹 
     * @param $img_dir  保存图片目录，如果有，就是需要获取图片，空则不需要获取
     */
    public function getData($request, $file_name = 'file', $file_dir = 'file' , $img_dir = '')
    {
        if ($request->file($file_name) == null) throw new Exception('请添加Excel表格......'); // return $this->returnApi(202, '请添加Excel表格......');

        //接收前台文件
        if (empty($_FILES[$file_name]['name'])) throw new Exception('上传文件不能为空'); //return $this->returnApi(202, "上传文件不能为空");
        if (empty($_FILES[$file_name]['size']) || $_FILES[$file_name]['size'] > 5242880) throw new Exception('上传文件不能大于5M'); //return $this->returnApi(202, "上传文件不能大于5M");

        //判断文件名
        $name = explode('.', $_FILES[$file_name]['name'])[1];
        if ($name !== 'xls' && $name !== 'xlsx') throw new Exception('上传文件后缀名不允许，只能上传 .xls 或 .xlsx 的文件'); //return $this->returnApi(202, "上传文件后缀名不允许，只能上传 .xls 或 .xlsx 的文件");

        // 这个方法是 自定义文件名 文件上传方法 。 将获取到的Excel文件 保存到/public/upload/book_import/ 文件中。
        $foldername =  $file_dir . '/' . date('Y-m-d'); //$file_name.'/'.date('Y-m-d')  存放路径，按日志存储
        $file = $request->file($file_name)->store($foldername);

        if ($file) {
            //$request->file($file_name)->getRealPath(); 获取临时文件地址
            $file_addr = public_path('uploads') . '/' . $file; //完整地址
             // Excel::load($file_addr, function ($reader) {return $reader->all();}); 
            $delTitle = 0; //指定头行数  删除它
            $excel = new Import($delTitle);
            Excel::import($excel, $file_addr);

            if ($excel->data) {
                $data = $excel->data->toArray(); //获取所有的数据（数组）
       
                //获取图片地址
                if($img_dir){
                    $img_data = $this->getExcelImg($file_addr , $img_dir);
                    $data = $this->setReturnData($data , $img_data , $delTitle);
                }
               
                return $data;
            }
            throw new Exception('导入失败');
        }
        throw new Exception('请添加Excel表格......'); //return $this->returnApi(202, "导入失败");
    }

    /**
     * 处理数据
     */
    public function setReturnData($data , $img_data , $delTitle){
        foreach($img_data as $key=>$val){
            $data[$key - $delTitle][array_keys($val)[0]] = array_values($val)[0];
        }
        return $data;
    }


    /**
     * 获取表格中的图片
     * $inputFileName excel 地址
     * $imageFilePath excel 图片保存路径
     */
    public function getExcelImg($inputFileName , $imageFilePath)
    {
        try {
            $objRead = IOFactory::createReader('Xlsx');

            $objSpreadsheet = $objRead->load($inputFileName);

            $objWorksheet = $objSpreadsheet->getSheet(0);

            $data = [];
            foreach ($objWorksheet->getDrawingCollection() as $drawing) {
                list($startColumn, $startRow) = Coordinate::coordinateFromString($drawing->getCoordinates());

                $imageFileName = $drawing->getCoordinates() . uniqid();

                switch ($drawing->getExtension()) {
                    case 'jpg':

                    case 'jpeg':

                        $imageFileName .= '.jpg';

                        $source = imagecreatefromjpeg($drawing->getPath());

                        imagejpeg($source, $imageFilePath . $imageFileName);

                        break;

                    case 'gif':

                        $imageFileName .= '.gif';

                        $source = imagecreatefromgif($drawing->getPath());

                        imagegif($source, $imageFilePath . $imageFileName);

                        break;

                    case 'png':

                        $imageFileName .= '.png';

                        $source = imagecreatefrompng($drawing->getPath());

                        imagepng($source, $imageFilePath . $imageFileName);

                        break;
                }


                $startColumn = letter_to_decimal($startColumn);

                $data[$startRow - 1][$startColumn] = substr($imageFilePath . $imageFileName , strlen(public_path('uploads')));
            }

            return $data;
        } catch (\Exception $e) {
            throw $e;
        }
    }


}